﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using MyAlbum.Model;
using MyAlbum.Services;
using MyAlbum.Utility;

namespace PersonalAlbum.Controllers
{
    public class AlbumsController : ApplicationController
    {
        private IAlbumService _albumService;
        public AlbumsController()
            : this(ObjectFactory.GetInstance<IAlbumService>())
        { }

        public AlbumsController(IAlbumService albumService)
        {
            this._albumService = albumService;
        }

        /// <summary>
        /// Show the create album form, an ajax method
        /// </summary>
        /// <param name="parentSection"></param>
        /// <returns>The create form HTML</returns>
        [Authorize(Roles = RolesManager.AdminRoles)]
        public ActionResult ShowCreate(string parentSection)
        {
            var model = (PersonalAlbumModel)ViewData.Model;
            model.Sections = WebCacheManager.Instance.GetSections();
            model.ParentSection = parentSection;
            model.ReturnUrl = Request.Params["returnUrl"];
            return PartialView("AddAlbum", model);
        }

        /// <summary>
        /// Show the update album form, an ajax method
        /// </summary>
        /// <param name="parentSection"></param>
        /// <returns>The update form HTML</returns>
        [Authorize(Roles = RolesManager.AdminRoles)]
        public ActionResult ShowUpdate(string id)
        {
            var model = (PersonalAlbumModel)ViewData.Model;
            model.Sections = WebCacheManager.Instance.GetSections();
            model.ReturnUrl = Request.Params["returnUrl"];
            model.CurrentAlbum = this._albumService.GetItemById(id);
            return PartialView("EditAlbum", model);
        }

        /// <summary>
        /// Delete an album by id
        /// </summary>
        /// <param name="id">The album id</param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize(Roles = RolesManager.AdminRoles)]
        // [ValidateAn tiForgeryToken()]
        public ActionResult Delete(string id)
        {
            var model = (PersonalAlbumModel)ViewData.Model;
            string sectionId = Request.Params["sectionId"];
            WebLogger.Trace("delete album:" + id);

            try
            {
                Album album = this._albumService.GetItemById(id);
                if (album != null)
                {
                    Utils.DeleteImage(album.Url);
                    this._albumService.DeleteItem(new Album() { Id = id });
                    WebLogger.Trace("album deleted");
                }
                else
                {
                    WebLogger.Warning("album " + id + " not found for delete");
                }
                return RedirectToAction("Index", new { sectionId = sectionId });
            }
            catch (Exception e1)
            {
                WebLogger.LogError(e1, "error deleting album");
                ViewData.ModelState.AddModelError("albumId", e1);
                model.ErrorMessage = model.Localize("Global.Error");
                return View("Index", LoadData(sectionId));
            }
        }
        [AcceptVerbs(HttpVerbs.Post)]
        // [ValidateAn tiForgeryToken()]
        [Authorize(Roles = RolesManager.AddItemsRoles)]
        public ActionResult Create()
        {
            var model = (PersonalAlbumModel)ViewData.Model;
            WebLogger.Trace("create album");
            string sectionId = Request.Params["sectionId"];
            try
            {
                Album album = new Album();
                UpdateModel<Album>(album, "Album");
                if (Request.Files["Album.Image"] != null &&
                    Request.Files["Album.Image"].ContentLength > 0)
                {
                    album.Url = Utils.SaveFile(Request.Files["Album.Image"]);
                }

                //album.Name = Request.Params["Album.Name"];
                //album.Description = Request.Params["Album.Description"];
                //album.Url = Request.Params["Album.Url"];
                //album.Visible = string.Compare(Request.Params["Album.Visible"], "true", true) == 0;
                //album.SectionId = Convert.ToInt32(Request.Params["Album.SectionId"]);
                this._albumService.AddItem(album, new ModelStateWrapper(ModelState));
                WebLogger.Trace("album created");
                return RedirectToAction("Index", new { sectionId = album.ParentId });
            }
            catch (Exception e1)
            {
                WebLogger.LogError(e1, "error creating album");
                model.ErrorMessage = model.Localize("Global.Error");
                return View("Index", LoadData(sectionId));
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        // [ValidateAn tiForgeryToken()]
        [Authorize(Roles = RolesManager.AdminRoles)]
        public ActionResult Update(string id)
        {
            var model = (PersonalAlbumModel)ViewData.Model;
            WebLogger.Trace("updating album");
            string sectionId = Request.Form["sectionId"];
            try
            {

                bool delete = Request.Form["Album.Delete"] == null ?
                    false :
                    Request.Form["Album.Delete"].Equals("true",
                    StringComparison.InvariantCultureIgnoreCase);
                Album album = this._albumService.GetItemById(id);
                if (album != null)
                {
                    if (delete)
                    {
                        Utils.DeleteImage(album.Url);
                        album.Url = null;
                    }
                    UpdateModel<Album>(album, "Album");
                    if (Request.Files["Album.Image"] != null &&
                        Request.Files["Album.Image"].ContentLength > 0)
                    {
                        if (!delete)
                        {
                            Utils.DeleteImage(album.Url);
                        }
                        album.Url = Utils.SaveFile(Request.Files["Album.Image"]);
                    }
                    this._albumService.UpdateItem(album, new ModelStateWrapper(ModelState));
                    WebLogger.Trace("album updated");
                    return RedirectToAction("Index", new { sectionId = album.ParentId });
                }
                else
                {
                    WebLogger.Warning("album " + id + " not found for update");
                    return RedirectToAction("Index");
                }
            }
            catch (Exception e1)
            {
                WebLogger.LogError(e1, "error updating album");
                model.ErrorMessage = model.Localize("Global.Error");
                return View("Index", LoadData(sectionId));
            }
        }

        //   [OutputCache(Duration=120000,VaryByParam="sectionId",VaryByCustom="lang")]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index(int page, string sectionId)
        {
            WebLogger.Trace("view albums");
            return View(LoadData(sectionId));

        }

        private PersonalAlbumModel LoadData(string sectionId)
        {
            var model = (PersonalAlbumModel)ViewData.Model;

            if (sectionId != null && sectionId != "all")
            {
                model.Albums = this._albumService.GetAlbumsBySectionId(sectionId);
                model.ParentSection = sectionId;
                ViewData["sectionId"] = sectionId;
            }
            else
            {
                model.Albums = this._albumService.GetItems();
            }

            if (((PersonalAlbumModel)ViewData.Model).User.AllowAdd())
            {
                model.Sections = WebCacheManager.Instance.GetSections();
            }
            return model;
        }

    }
}
